package com.aiti.lulian.controller;



import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.workflow.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/workflow")
public class WorkflowController extends WebController {

    @Autowired
    private WorkflowEngine workflowEngine;

    @PostMapping("/start")
    public Message startProcess(
            @RequestParam String processDefinitionId,
            @RequestParam String businessKey,
            @RequestBody Map<String, Object> variables,
            String userId,
            @RequestParam String businessType) {

        if(StringUtils.isEmpty(userId)){
            userId = findUserId();
        }

        workflowEngine.startProcess(
                processDefinitionId, businessKey, variables, userId, businessType);
        return Message.success();
    }


    @PostMapping("/task/complete")
    public Message completeTask(
            @RequestBody CompleteTaskRequest request) {


        if(StringUtils.isEmpty(request.getUserId())){
            request.setUserId(findUserId());
        }

        workflowEngine.completeTask(request.getTaskId(), request.getVariables(),
                request.getComment(), request.getUserId());
        return Message.success();
    }

    @PostMapping("/task/reject")
    public Message rejectTask(
            @RequestBody RejectTaskRequest request
            ) {

        if(StringUtils.isEmpty(request.getUserId())){
            request.setUserId(findUserId());
        }

        workflowEngine.rejectTask(request.getTaskId(), request.getRejectToNodeId(),
                request.getVariables(), request.getComment(), request.getUserId(), request.isTerminateProcess());
        return Message.success();
    }

    @GetMapping("/instance/status")
    public Message getProcessStatus(
            @RequestParam String instanceId) {

        WorkflowEngine.ProcessStatus status = workflowEngine.getProcessStatus(instanceId);
        return Message.success(status);
    }

    @GetMapping("/task/reject-options")
    public Message getRejectOptions(
            @RequestParam String taskId) {

        List<WorkflowEngine.RejectOption> options = workflowEngine.getRejectOptions(taskId);
        return Message.success(options);
    }





}
